package com.linq.cool.common.core.exception;

import com.linq.cool.common.core.domain.Result;
import com.linq.cool.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * @Author: yqlin
 * @Date: 2020/12/29 16:58
 * @Description: 全局异常处理器
 * @Version: 1.0.0
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public Result<Object> validatedBindException(BindException e) {
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return Result.fail(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> validExceptionHandler(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        return Result.fail(message);
    }

    /**
     * 权限异常
     */
    @ExceptionHandler(PreAuthorizeException.class)
    public Result<Object> preAuthorizeException(PreAuthorizeException e) {
        return Result.fail("没有权限，请联系管理员授权");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<Object> notFount(RuntimeException e) {
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }
        log.error("运行时异常:", e);
        return Result.fail("运行时异常:" + e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) throws Exception {
        log.error(e.getMessage(), e);
        return Result.fail("服务器错误，请联系管理员");
    }

    /**
     * 捕获并处理未授权异常
     *
     * @param e 授权异常
     *
     * @return 统一封装的结果类, 含有代码code和提示信息msg
     */
    @ExceptionHandler(UnauthorizedException.class)
    public Result<Object> handle401(UnauthorizedException e) {
        return Result.fail(401, e.getMessage());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result<Object> handleDuplicateKeyException(DuplicateKeyException e) {
        log.error(e.getMessage(), e);
        return Result.fail("数据库中已存在该记录");
    }

    @ExceptionHandler(ValidateCodeException.class)
    public Result<Object> handleCaptcha(ValidateCodeException e) {
        return Result.fail(e.getMessage());
    }


    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    @ResponseStatus(code = HttpStatus.METHOD_NOT_ALLOWED)
    public Result handleException(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return Result.fail("不支持' " + e.getMethod() + "'请求");
    }


    /**
     * 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<Object> businessException(BusinessException e) {
        if (StringUtils.isNull(e.getCode())) {
            return Result.fail(e.getMessage());
        }
        return Result.fail(e.getCode(), e.getMessage());
    }

    /**
     * 基础异常
     */
    @ExceptionHandler(BaseException.class)
    public Result<Object> baseException(BaseException e) {
        return Result.fail(e.getMessage());
    }
}
